package com.zhl.study.module;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * @description 表示服务
 * @Author: z156940l@outlook.com
 * @className ServiceDescriptor
 * @Date: 2024/5/20 9:45
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ServiceDescriptor {

    //类名
    private String clazz;
    //方法名
    private String method;
    //返回类型
    private String returnType;
    //参数类型
    private String[] parameterTypes;

    /**
     * 通过clazz 和 method 抽取出方法的输入输出参数，生成ServiceDescript
     * @param clazz
     * @param method
     * @return
     */
    public static ServiceDescriptor from(Class clazz, Method method){
        ServiceDescriptor sdp = new ServiceDescriptor();
        sdp.setClazz(clazz.getName());
        sdp.setMethod(method.getName());
        sdp.setReturnType(method.getReturnType().getName());

        Class[] parameterClasses = method.getParameterTypes();
        String[] parameterTypes = new String[parameterClasses.length];
        for(int i=0;i<parameterClasses.length;i++){
            parameterTypes[i] = parameterClasses[i].getName();
        }
        sdp.setParameterTypes(parameterTypes);

        return sdp;
    }

    @Override
    public boolean equals(Object o) {
        if(this == o)return true;
        if(o == null || getClass() != o.getClass()) return false;

        ServiceDescriptor that = (ServiceDescriptor)o;
        return this.toString().equals(o.toString());
    }

    @Override
    public int hashCode() {
        return toString().hashCode();
    }

    @Override
    public String toString() {
        return     "clazz="+ clazz
                + ",method="+ method
                +",returnType="+ returnType
                +",parameterTypes="+ Arrays.toString(parameterTypes);
    }
}
